<?php
class IndexController extends RCMS_Core_BaseController {

	public function init() {
		parent::init();
		$this->_model = new IndexModel();
		$this->checkUpdateContentTime();
	}

	/**
	 * Main action
	 *
	 */
	public function indexAction() {
		//things that are needed for both types of users (logged in and not logged)
		$searchResult      = null;
		$allowModification = $this->_session->isLogged;
		$websiteUrl        = $this->getWebSiteUrl();
		$seoParser         = new RCMS_Object_Parser_SeoParser();
		$pageContent       = '';

		//processing search results
		if($this->_session->searchResult != null) {
			$searchResult = $this->_session->searchResult;
		}

		//proccessing member errors
		if(isset($this->_session->memberError)) {
			$this->view->memberError = $this->_session->memberError;
			unset($this->_session->memberError);
		}
		if(isset($this->_session->memberDownloadError)) {
			$this->view->memberError = $this->_session->memberDownloadError;
			unset($this->_session->memberDownloadError);
		}

		//Here we are making a page! Most important part
		//if no requested page (ex: http://www.site_name.com/) then get default page from config
		$requestedPage = urlencode($this->getRequest()->getParam('page', unserialize(Zend_Registry::get('config'))->website->website->defaultPage));
		$this->_validateReqPage($requestedPage);

		$pageData = $this->_grubPageData(RCMS_Tools_Tools::stripSlashesIfQuotesOn($requestedPage));
		//If page not found then send 404 NOT FOUND response
		if(!$pageData) {
			$pageData = $this->_show404Page($allowModification);
		}
		$this->_checkSecurity($pageData);
		$pageData['websiteUrl']   = $websiteUrl;
		$pageData['currentTheme'] = $this->_model->selectCurrentTheme();
		//lounching parser
		//putting additional options
		$additionalOptions = array(
			'productFilter' => $this->_session->productFilter,
			'resaveRaw'     => ($this->_session->resaveRaw) ? true : false
		);
		$this->_session->resaveRaw = false;
		$parser = new RCMS_Object_Parser_Parser($pageData['templateContent'], $pageData, $allowModification, $searchResult, $this->_session->langId, $this->_session->memberLogged, $additionalOptions);

		$pageContent = $parser->processContent();
		//handle forms messages and search results
		$this->_processFormsMessagesAndCleanSearch();
		//check wether users looged in or not and making some cool stuff
		if(!$this->_session->isLogged && !$this->_session->memberLogged) {
			//disabling system layout for not logged users
			$this->_helper->layout->disableLayout();
			//do a little append to final page body
			$pageContent = $this->_appendBody($pageContent, $parser->getUsingConcatCss(), $requestedPage, $pageData['h1']);
		}
		else {
			//check for two default system pages
			$this->_checkIfNoCategoryAndIndexExist();
			$this->_checkForDraftCategory();
			$this->_session->currentThemeName = $pageData['currentTheme'];
			$cantDelete = $this->_session->cantDelete;
			unset($this->_session->cantDelete);
			$this->_getServices();
			//setting view vars for logged user
			$this->view->loggedTitle     = $pageData['header_title'];
			$this->view->cantDelete      = $cantDelete;
			$this->view->servicesContent = $this->_session->servicesContent;
			$this->view->cntDraftPages   = $this->_countDraftPages();
			$this->view->newQuotesCount  = $this->_countNewQuotes();
			$this->view->hidePanel       = (isset($this->_session->hidePanel) && $this->_session->hidePanel === true) ? true : false;
			//seo parser routine
			$seoParser->refreshHtAccess();
		}
		//commont variables
		$this->view->content  = $pageContent;
		$this->view->pageData = $pageData;
		$this->view->statUrl  = $requestedPage;
		$this->view->statKey  = $pageData['h1'];

		//seo routine
		$seoParser->makeCanonicRules();
		$this->_checkForPRSFile();

		$shopingCart = new RCMS_Object_Shopping_ShoppingCart();
		if( !isset($this->_session->userReferrerUrl)){
			$this->_session->userReferrerUrl = $this->getRequest()->getHeader('referer');
		}

	}

	/**
	 * Checks if requested page is one from the forbiden pages then redirects to
	 * website main page.
	 *
	 * @param string $reqPage page url
	 */
	private function _validateReqPage($reqPage) {
		if(in_array($reqPage, RCMS_Object_QuickConfig_QuickConfig::$forbiddenUrls)) {
			$this->_redirect($this->getWebSiteUrl(), array('exit' => true));
		}
	}

	private function _checkSecurity($pageData) {
		if($pageData['protected'] == '1') {
			$memLandingPageData = $this->_model->selectMemberLandingPage();
			if(is_array($memLandingPageData) && !empty ($memLandingPageData)) {
				if(!$this->_session->isLogged && !$this->_session->memberLogged) {
					$this->_redirect($this->_websiteUrl . $memLandingPageData['url'] . '.html', array('exit' => true));
				}
			}
			else {
				if(!$this->_session->isLogged && !$this->_session->memberLogged) {
					$this->_redirect($this->_websiteUrl);
				}
			}
		}
	}

	/**
	 * Check if it is time to publish container
	 *
	 */
	public function checkUpdateContentTime() {
		if(isset($this->_session->updateContentDate)) {
			$updateDate  =   $this->_session->updateContentDate;
			$currentDate = date("m-d-Y");
			if($currentDate > $updateDate ) {
				$this->_model->updatePublishedContent();
				$this->_session->updateContentDate = $currentDate;
			}
		}
		else {
			$this->_session->updateContentDate = date("m-d-Y");
			$this->_model->updatePublishedContent();
		}
	}

	private function _countNewQuotes() {
		$quotesCount = $this->_model->countNewQuotes();
		return intval($quotesCount);
	}


	/**
	 * Main action for news pages
	 *
	 * @todo refactor this method!
	 *
	 */
	public function newsAction() {
		$parseNewsList = false;
		$templateName = unserialize(Zend_Registry::get('config'))->news->news->templateName;
		$allowModification = true;
		// If this is a regular user - disable layout and tell parser do not add links to containers
		if(!$this->_session->isLogged) {
			$allowModification = false;
			$this->_helper->layout->disableLayout();
		}
		$requestedNewsPage = $this->getRequest()->getParam('news_url');
		//if no requested page (ex: http://www.site_name.com/) then get default page from config
		if(empty($requestedNewsPage)) {
			$requestedNewsPage = unserialize(Zend_Registry::get('config'))->news->news->defaultNewsPage;
			$parseNewsList = true;
		}

		if(!$parseNewsList) {
			$newsData = $this->_grubNewsPageData($requestedNewsPage);
		}
		else {
			$newsData = null;
		}

		$newsData['websiteUrl'] = $this->view->websiteUrl;
		$this->view->loggedTitle = (isset($newsData['newsTitle'])? $newsData['newsTitle'] : "News Index");
		//set current theme name for parser
		$newsData['currentTheme'] = $this->_model->selectCurrentTheme();
		//set current theme name to session also.s
		$this->_session->currentThemeName = $newsData['currentTheme'];
		//get news template content
		if(!empty($templateName)) {
			$templateObj = new RCMS_Object_Template_Template($this->_model->selectTemplateByName($templateName));
		}else {
			$templateObj =  new RCMS_Object_Template_Template($this->_model->selectTemplateByName('news'));
		}
		$newsData['requestedNewsPage'] = $requestedNewsPage;
		$newsData['templateId'] = $templateObj->getId();
		$parser = new RCMS_Object_Parser_Parser($templateObj->getContent(), $newsData, $allowModification);
		//setting view variables
		$this->view->content = $parser->processContent($parseNewsList, true);
		$this->view->newsData = $newsData;
		if(!$this->_session->isLogged) {
			$htmlHead = '<link href="' .$this->view->websiteUrl . 'system/js/thickbox/thickbox.css" media="screen" rel="stylesheet" type="text/css" />' . "\n" .
				'<script type="text/javascript" src="' .$this->view->websiteUrl . 'system/js/jquery/jquery.js"></script>' . "\n" .
				'<script type="text/javascript" src="' .$this->view->websiteUrl . 'system/js/thickbox/thickbox.js"></script>' . "\n";
			$this->view->content = preg_replace("~<head>(.*)<\/head>~s", "<head>" . $htmlHead . "$1</head>\n", RCMS_Tools_Tools::stripSlashesIfQuotesOn($this->view->content));
		}
	}


	/**
	 * Get all page's data
	 *
	 * @param String $requestedPage
	 * @return Array
	 */
	protected function _grubNewsPageData($requestedNewsPage) {
		if(!empty ($requestedNewsPage)) {
			$ext = $this->_getExtension($requestedNewsPage);
			if($ext === '.html') {
				$requestedNewsPage = str_replace('.html', '', $requestedNewsPage);
			}
			else {
				return '';
			}
		}
		$requestedNewsPage = $this->_proccessUrl($requestedNewsPage);
		$requestedData     = $this->_model->getRequestedNewsData($requestedNewsPage);
		if(!$requestedData) {
			$requestedNewsPage = explode('-', $requestedNewsPage);
			if(sizeof($requestedData) <= 1) {
				return '';
			}
			unset($requestedNewsPage[array_search(end($requestedNewsPage), $requestedNewsPage)]);
			$requestedNewsPage = implode('-', $requestedNewsPage);
			$requestedData     = $this->_model->getRequestedNewsData($requestedNewsPage, true);
		}
		return $requestedData;
	}

	/**
	 * @method Proccess Url replacing spaces to '-'
	 *
	 * @param  String $search
	 * @param  String $replace
	 * @return String ''
	 */
	protected function _proccessUrl($url, $search=' ', $replace='-') {
		return str_replace($search, $replace,trim($url));
	}

	/**
	 * Check url on .html extension
	 *
	 * @param  string $url
	 * @return string
	 */
	private function _getExtension($url) {
		$pu = parse_url($url);
		preg_match('~\.[a-z]+\.?$~si', $pu['path'], $matches);
		return isset($matches[0]) ? $matches[0] : false;
		//return substr($pu['path'], (strlen($pu['path'])-5));
	}

	/**
	 * Checks if page and category exist '-'
	 *
	 * @return void;
	 */
	private function _checkIfNoCategoryAndIndexExist() {
		//get data for no category page and for no-category category
		$noCategoryPage = $this->_model->getPageByUrl('no-category');
		$noCategoryCategory = $this->_model->selectCategoryByName('no category');
		//if category page exists
		if(!$noCategoryPage) {
			$templateId = $this->_model->selectTemplateByName('default');
			if($templateId) {
				if($noCategoryCategory) {
					$_categoryId = $noCategoryCategory['id'];
				}
				else {
					$this->_model->insertNewCategory('no category');
				}
				$pageObj = new RCMS_Object_Page_Page();
				$pageObj->setTemplateId($templateId);
				$pageObj->setCategoryId("-1");
				$pageObj->setNavName('no category');
				$pageObj->setMetaDescription('');
				$pageObj->setMetaKeywords('');
				$pageObj->setHeaderTitle('no category');
				$pageObj->setH1Tag('no category');
				$pageObj->setUrl('no-category');
				$pageObj->setShortDescription('');
				$pageObj->setOwner(0);
				$pageObj->setIs404Page(0);
				$pageObj->setShowInMenu(1);
				$pageObj->setOrder(0);
				$pageObj->setStaticOrder(100);
				$pageObj->setWeight(0);
				$pageObj->setSeosambaRuleId(0);
				$pageObj->setSiloId(0);
				$pageObj->setLastUpdate(date("Y-m-d H:i:s", time()));
				$pageObj->save();
			}
		}
		else // check if category no category exists
		{
			if(!$noCategoryCategory) {
				$this->_model->insertNewCategory('no category');
				$pageObj = new RCMS_Object_Page_Page($noCategoryPage->id);
				$pageObj->setCategoryId(-1);
				$pageObj->save();
			}
		}
	}


	/**
	 * Checks if rss file exists
	 *
	 * @return void;
	 */
	private function _checkForPRSFile() {
		$config = unserialize(Zend_Registry::get('config'));
		$path = $config->website->website->path . 'tmp/';
		if(!file_exists($path . 'pfs.prs')) {
			try {
				RCMS_Tools_FilesystemTools::saveFile($path . 'pfs.prs', 'forprsculpting');
			}
			catch (Exception $e) {
				return;
			}
		}
	}

	/**
	 * Check system for draft category.
	 *
	 */
	private function _checkForDraftCategory() {
		$draftCategoryPage = $this->_model->getPageByUrl(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl);
		$draftCategory = $this->_model->selectCategoryByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		if(!$draftCategoryPage) {
			$templateId = $this->_model->selectTemplateByName('category');
			if($templateId) {
				if($draftCategory) {
					$draftCategoryId = $draftCategory['id'];
				}
				else {
					$draftCategoryId = $this->_model->insertNewCategory(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				}
				$page = new RCMS_Object_Page_Page();
				$page->setTemplateId($templateId);
				$page->setCategoryId($draftCategoryId);
				$page->setNavName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setMetaDescription('');
				$page->setMetaKeywords('');
				$page->setHeaderTitle(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setH1Tag(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$page->setUrl(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryUrl);
				$page->setShortDescription('');
				$page->setOwner(1);
				$page->setIs404Page(0);
				$page->setShowInMenu(1);
				$page->setOrder(100);
				$page->setStaticOrder(100);
				$page->setWeight(0);
				$page->setSeosambaRuleId(0);
				$page->setSiloId(0);
				$page->setLastUpdate(date("Y-m-d H:i:s", time()));
				$page->save();
			}
		}
		else {
			if(!$draftCategory) {
				$catId = $this->_model->insertNewCategory(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
				$pageObj = new RCMS_Object_Page_Page($draftCategoryPage->id);
				$pageObj->setCategoryId($catId);
				$pageObj->save();
			}
		}
	}

	/**
	 * Append needed things to the final unlogged-user's html
	 *
	 * @param string $pageContent
	 * @return string
	 */
	private function _appendBody($pageContent, $usingConcatCss, $pageUrl, $pageh1) {
		$websiteUrl = $this->getWebSiteUrl();

		$pageUrl = ($pageUrl) ? str_replace($this->_getExtension($pageUrl), '.html', $pageUrl) : $pageUrl;

		$htmlHead = '';
		$htmlHead .= '<link rel="canonical" href="'.$websiteUrl . $pageUrl .'"/>';
		if(!$usingConcatCss) {
			$htmlHead .= '<link href="' . $websiteUrl . 'system/js/thickbox/thickbox.css" media="screen" rel="stylesheet" type="text/css" />' . "\n";
		}
		$htmlHead .= $this->_loadJQ();
		$htmlHead .= '<script type="text/javascript" src="' . $websiteUrl . 'system/js/complex.js"></script>' . "\n";
        $pageContent = preg_replace("~<head>(.*)<\/head>~sU", "<head>" . $htmlHead . "$1</head>\n", $pageContent);
		$pageContent = str_replace(array('</body>', '</html>'), '', $pageContent);
		$pageContent .= '
			<input type="hidden" id="hid-main-wsurl" value="'. $websiteUrl . '" />
			<script type="text/javascript">
				replaceNSP();
			</script>
			</body>
			</html>
		'; //removed statCall("'.$pageUrl.'","'.$pageh1.'"); from start script for David
		return $pageContent;
	}

	/**
	 * Load proper jQuery library
	 *
	 * If system can use jQuery hosted on Google then this one will be loaded
	 * Otherwise local copy of jQuery will be loaded
	 *
	 * @return string
	 */
	private function _loadJQ() {
		return (false !== @file_get_contents(RCMS_Object_QuickConfig_QuickConfig::G_JQ_HOSTED_URL)) ? '<script type="text/javascript" src="' . RCMS_Object_QuickConfig_QuickConfig::G_JQ_HOSTED_URL . '"></script>' . "\n" : '<script type="text/javascript" src="' . $this->getwebsiteUrl() . 'system/js/jquery/jquery.js"></script>' . "\n";
	}

	/**
	 * Get needed content for services menu
	 *
	 */
	private function _getServices() {
		//trying to get services and paste it to the cpanel
		if(!isset($this->_session->servicesContent) || $this->_session->servicesContent = '<ul><li>No services.</li></ul>') {
			$servicesContent = $this->_getCustomServices();
			if(!$servicesContent) {
				$servicesContent = @RCMS_Tools_Tools::stripSlashesIfQuotesOn(file_get_contents(RCMS_Object_QuickConfig_QuickConfig::SERVICES_URL));
				if(strpos($servicesContent, '<ul', 0) === false) {
					$servicesContent = '';
				}
			}
			$this->_session->servicesContent = (!(empty($servicesContent))) ? $servicesContent : '<ul><li>No services.</li></ul>'  ;
		}
	}

	/**
	 * Shows correct 404 page
	 *
	 * @param <type> $isLogged
	 * @return <type>
	 */
	private function _show404Page($isLogged) {
		$websiteUrl = $this->getWebSiteUrl();
		$this->getResponse()->setHeader('HTTP/1.1', '404 Not Found');
		$this->getResponse()->setHeader('Status', '404 File not found');
		$page404Url = $this->_model->getPage404Url();
		if(!$page404Url) {
			if(!$isLogged) {
				$this->_helper->getHelper('layout')->disableLayout();
				$this->getResponse()->setBody("
					<div style=\"text-align: center;\">
						<span style=\"color: #ff0000; font-weight: bold; font-size: 20px; \">Error 404. Page not found.</span><br/>
						<a href=\"". $websiteUrl ."\">Back to home page</a>
					</div>
				");
			}
			else {
				$this->_helper->getHelper('layout')->disableLayout();
				$this->getResponse()->setBody("
					<div style=\"text-align: center;\">
						<span style=\"color: #ff0000; font-weight: bold; font-size: 20px; \">Error 404. Page not found.</span>
						<span style=\"color: #cecece; font-size: 12px;\">
							<br/>You can costumize this page - just create a page and assign it as 404 error page
							<br/>Use the checkbox on the create/update page screen.
						</span><br/>
						<a href=\"". $websiteUrl ."\">Back to home page</a>
					</div>
				");
			}
			return;
		}
		return $this->_grubPageData($page404Url . '.html');
	}

	/**
	 * Count pages in drft
	 * @return integer
	 */
	private function _countDraftPages() {
		$draftCategory = $this->_model->selectCategoryByName(RCMS_Object_QuickConfig_QuickConfig::$draftCategoryName);
		return $this->_model->countDraftPages($draftCategory['id']);
	}


	/**
	 * Try to get agency's custom services
	 *
	 * @return mixed Returns services content if it exists or false
	 */
	private function _getCustomServices() {
		$result = $this->_model->selectServicesContent();
		return (!empty($result) ? $result[0]['servicesContent'] : false);
	}

	/**
	 * Get all page's data
	 *
	 * @param string $requestedPage
	 * @return array
	 */
	protected function _grubPageData($requestedPage) {
		$requestedPage = (empty ($requestedPage)) ? $this->_config->website->website->defaultPage : $requestedPage;
		$cacheId       = 'page_' . preg_replace('/[^_A-Za-z0-9]/', '', $requestedPage);

		$reqPageExtension = $this->_getExtension($requestedPage);

		if(!in_array($reqPageExtension, RCMS_Object_QuickConfig_QuickConfig::$allowedPageExtensions)) {
			return null;
		}

		$requestedPage = str_replace($reqPageExtension, '', $requestedPage);

		if(!$this->_session->isLogged || $this->_session->memberLogged) {
			if(!($requestedData = $this->_cache->load($cacheId))) {
				$requestedData = $this->_model->getRequestedData($requestedPage);
				$this->_cache->save($requestedData, $cacheId);
			}
		}
		else {
			$requestedData = $this->_model->getRequestedData($requestedPage);
		}
		return $requestedData;
	}

	/**
	 * Doing routine with form messages and cleaning search results
	 *
	 */
	private function _processFormsMessagesAndCleanSearch() {
		//unset search result variable after processing content
		unset($this->_session->searchResult);
		//Start Handling Errors For Forms
		if($this->_session->formSmtpMessage) {
			$this->view->formSmtpMessage = $this->_session->formSmtpMessage;
			unset($this->_session->formSmtpMessage);
		}
		if($this->_session->formErrorMessage) {
			$this->view->formErrorMessage = $this->_session->formErrorMessage;
			unset($this->_session->formErrorMessage);
		}
		if($this->_session->formSuccessMessage) {
			$this->view->formSuccessMessage = $this->_session->formSuccessMessage;
			unset($this->_session->formSuccessMessage);
		}
		if($this->_session->formCaptchaNotValid) {
			$this->view->formCaptchaNotValid = $this->_session->formCaptchaNotValid;
			unset($this->_session->formCaptchaNotValid);
		}
		if($this->_session->formEmailNotValid) {
			$this->view->formEmailNotValid = $this->_session->formEmailNotValid;
			unset($this->_session->formEmailNotValid);
		}
	}
}

